var express = require('express');
var router = express.Router();
const autoprefixer = require('autoprefixer')
const postcss = require('postcss')
const precss = require('precss')
const stylefmt = require('stylefmt');
const postcssFlexbugsFixes = require('postcss-flexbugs-fixes');
const {mdRender} = require('../utils/utils')
// 默认编译配置
const overrideBrowserslist = ["> 1%", "last 2 versions", "not ie <= 10"];

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.render('autoprefixer',{overrideBrowserslist})
});
router.post('/', function(req, res, next) {
  const css = req.body.css;
  const isPreview = req.body.isPreview === 'true' || false;
  const req_overrideBrowserslist = req.body.overrideBrowserslist;
  
  let browserslist = overrideBrowserslist;
  if(req_overrideBrowserslist){
    try {
      browserslist = JSON.parse(req_overrideBrowserslist)
    } catch (error) {
      console.log(`JSON.parse(req.body.overrideBrowserslist) 出错：${error.message}`)
      browserslist = overrideBrowserslist
    }
  }
  postcss([precss, autoprefixer({overrideBrowserslist: browserslist}),postcssFlexbugsFixes,stylefmt])
  .process(css)
  .then(result => {
    if(isPreview){ //返回可预览的
      res.end(mdRender(result.css,'css'))
    } else{
      res.end(result.css)
    }
  })
  .catch(err =>{
    res.end(`编译出错：${err.message}`)
  })
});

module.exports = router;